<template>
  <div class="app-container">
    <div style="display: flex; justify-content: space-between">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="addRulesClick"
            v-hasPermi="['attendance:rule:trips:add']"
            >新增外出、出差规则</el-button
          >
        </el-col>
      </el-row>
      <!-- 请输入新增外出、出差规则规则名称输入框-->
      <div>
        <el-input
          v-model="queryParams.name"
          style="max-width: 200px; margin-left: 10px"
          placeholder="请输入规则名称"
          @change="handleQuery"
        >
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="postList"
      :default-sort="{ prop: 'id', order: 'descending' }"
    >
      <el-table-column
        label="规则名称"
        align="center"
        prop="name"
        width="180"
      />
      <el-table-column label="规则内容" align="center" prop="createTime">
        <template #default="scope">
          <div>
            {{
              scope.row.clock == 0 ? "外出、出差无需打卡" : "外出、出差需打卡"
            }}
          </div>
          <div v-if="scope.row.clock != 0">
            {{ (type = 1 ? "根据班次的上下班时间打卡" : "离岗或到岗需打卡") }}
          </div>
          <div v-if="scope.row.clock != 0">
            外出、出差打卡时间范围: 开始前{{ scope.row.startHoursNum }}小时{{
              scope.row.startMinutesNum
            }}分钟，结束后{{ scope.row.endHoursNum }}小时{{
              scope.row.endMinutesNum
            }}分钟
          </div>
        </template>
      </el-table-column>

      <el-table-column label="应用范围" align="center">
        <template #default="scope">
          <!-- <span>{{ scope.row.groupIds }}</span> -->
          <span
            style="margin-left: 10px"
            v-for="item in scope.row.groupIds"
            :key="item"
            >{{ handleGroupIdsShow(item) }}</span
          >
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['attendance:rule:trips:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['attendance:rule:trips:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修班次对话框 -->
    <el-drawer :title="title" v-model="open" direction="rtl">
      <template #default>
        <div>
          <div>
            <el-form :model="businessForm" :rules="rules" ref="postRef">
              <el-form-item label="规则名称" prop="name">
                <el-input
                  v-model="businessForm.name"
                  placeholder="请输入"
                  maxlength="30"
                  show-word-limit
                  style="width: 240px"
                />
              </el-form-item>

              <el-form-item label="应用范围" prop="groupIds">
                <div style="display: flex">
                  <el-select
                    placeholder="请选择"
                    style="width: 150px"
                    v-model="application"
                  >
                    <el-option
                      v-for="item in options2"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <el-select
                    multiple
                    filterable
                    v-model="businessForm.groupIds"
                    placeholder="未设置"
                    style="margin-left: 10px; width: 240px"
                  >
                    <el-option
                      v-for="item in groupList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="负责人" prop="principalIds">
                <el-select
                  multiple
                  filterable
                  v-model="businessForm.principalIds"
                  placeholder="未设置"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in principalSelectList"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>

          <div style="display: flex; align-items: center; font-size: 14px">
            <p>外出、出差需打卡</p>
            <el-switch
              v-model="isClock"
              size="small"
              style="margin-left: 10px"
              @change="handleIsClock"
            />
          </div>
        </div>
        <!-- 允许外出、出差需打卡隐藏内容 -->
        <div style="font-size: 14px" v-if="isClock == true">
          <div style="display: flex; flex-direction: column">
            <span> 打卡规则 </span>
            <el-radio-group v-model="businessForm.type">
              <el-radio :value="1">根据班次的上下班时间打卡</el-radio>
              <el-radio :value="2">离岗或到岗需打卡</el-radio>
            </el-radio-group>
          </div>
          <div>
            <p>打卡范围</p>
            <div>
              <span style="margin-bottom: 10px">开始前</span>
              <div style="margin: 10px 0">
                <cascader-timeSe
                  :endHour="24"
                  :endMinute="59"
                  :widthStyle="300"
                  :defaultSelectedTime="defaultStart"
                  @timeChange="handleBeforeStart"
                />
              </div>
              <span style="margin-top: 10px">结束后</span>
              <div style="margin: 10px 0">
                <cascader-timeSe
                  :endHour="24"
                  :endMinute="59"
                  :widthStyle="300"
                  :defaultSelectedTime="defaultEnd"
                  @timeChange="handleAfterEnd"
                />
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup name="Post">
import { updatePost } from "@/api/system/post";
import {
  getOutsideListApi,
  addOutsideApi,
  delOutsideApi,
  getOutsideByIdApi,
  updateOutsideApi,
} from "@/api/attendance/business";
import { getGroupListApi } from "@/api/attendance/attendance";
import { getOrgSearchAgApi } from "@/api/attendance/shift";
import { Search } from "@element-plus/icons-vue";
import { ref } from "vue";
import cascaderTimeSe from "../cascaderTimeSe.vue";

const { proxy } = getCurrentInstance();

const postList = ref([]);
const open = ref(false);
const loading = ref(true);
// 外出、出差开关按钮
const isClock = ref(false);
const total = ref(0);
const title = ref("");
const application = ref("1");
const businessForm = ref({
  name: "",
  groupIds: [], //应用范围-考勤组id集合
  principalIds: [], //负责人id
  clock: 0, //0：外出、出差无需打卡 1：外出、出差需打卡
  type: 1, //打卡规则 1：根据班次的上下班时间打卡 2：离岗或到岗需打卡
  startHoursNum: undefined, //开始前-时
  startMinutesNum: undefined, //开始前-分
  endHoursNum: undefined, //结束后-时
  endMinutesNum: undefined, //结束后-分
});
const defaultStart = ref([]);
const defaultEnd = ref([]);

/**
 * 重置需打卡部分的参数
 */
const resetDepartment = () => {
  businessForm.value.type = undefined;
  businessForm.value.startHoursNum = undefined;
  businessForm.value.startMinutesNum = undefined;
  businessForm.value.endHoursNum = undefined;
  businessForm.value.endMinutesNum = undefined;
};

watch(
  () => isClock.value,
  (newValue) => {
    if (newValue == true) {
      businessForm.value.clock = 1;
    } else if (newValue == false) {
      businessForm.value.clock = 0;
      resetDepartment();
    }
  },
  { deep: true, immediate: true }
);

/**
 * 外出、出差开关
 */
const handleIsClock = () => {
  // if (isClock.value == true) {
  //   businessForm.value.clock = 1;
  // } else if (isClock.value == false) {
  //   businessForm.value.clock = 0;
  //   businessForm.value.type = undefined;
  //   businessForm.value.startHoursNum = undefined;
  //   businessForm.value.startMinutesNum = undefined;
  //   businessForm.value.endHoursNum = undefined;
  //   businessForm.value.endMinutesNum = undefined;
  // }
};

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: "",
  },
  rules: {
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    groupIds: [
      { required: false, message: "应用范围不能为空", trigger: "change" },
    ],
    principalIds: [
      { required: true, message: "负责人不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, rules } = toRefs(data);
// 应用范围下拉框option
const options2 = [
  {
    value: "1",
    label: "考勤组",
  },
];

const groupList = ref([]);
/**
 * 获取所有考勤组
 */
const getGroupList = () => {
  getGroupListApi().then((res) => {
    groupList.value = res.data;
  });
};

const principalSelectList = ref([]);
/**
 * 获取有管理考勤打卡资格的用户信息
 */
const getOrgSearchAg = () => {
  getOrgSearchAgApi().then((res) => {
    principalSelectList.value = res.data;
  });
};

/**
 * 打卡范围 开始前 结束后
 * @param val
 */
const handleBeforeStart = (val) => {
  businessForm.value.startHoursNum = val[0];
  businessForm.value.startMinutesNum = val[1];
};

const handleAfterEnd = (val) => {
  businessForm.value.endHoursNum = val[0];
  businessForm.value.endMinutesNum = val[1];
};

/** 查询出差、外出规则列表 */
function getList() {
  loading.value = true;
  getOutsideListApi(queryParams.value).then((response) => {
    postList.value = response.rows || [];
    total.value = Number(response.total);
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  businessForm.value = {
    name: "",
    groupIds: [],
    principalIds: [],
    clock: 0,
    type: undefined,
    startHoursNum: undefined,
    startMinutesNum: undefined,
    endHoursNum: undefined,
    endMinutesNum: undefined,
  };

  isClock.value = false;
  defaultStart.value = [0, 0];
  defaultEnd.value = [0, 0];
  proxy.resetForm("postRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 新增按钮操作 */
function addRulesClick() {
  reset();
  open.value = true;
  title.value = "新增外出、出差规则";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const postId = row.id;

  getOutsideByIdApi(postId).then((response) => {
    businessForm.value = response.data;
    defaultStart.value = [
      Number(businessForm.value.startHoursNum),
      Number(businessForm.value.startMinutesNum),
    ];
    defaultEnd.value = [
      Number(businessForm.value.endHoursNum),
      Number(businessForm.value.endMinutesNum),
    ];
    businessForm.value.groupIds = businessForm.value.groupIds.map((v) =>
      String(v)
    );
    businessForm.value.principalIds = businessForm.value.principalIds.map((v) =>
      String(v)
    );
    businessForm.value.clock == 1
      ? (isClock.value = true)
      : (isClock.value = false);
    open.value = true;
    title.value = "编辑外出、出差规则";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["postRef"].validate((valid) => {
    if (valid) {
      if (businessForm.value.id != undefined) {
        updateOutsideApi(businessForm.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOutsideApi(businessForm.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const postIds = row.id;
  proxy.$modal
    .confirm('是否确认删除外出、出差规则"' + row.name + '"的数据项？')
    .then(function () {
      return delOutsideApi(postIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/**
 * 计算表格应用范围
 * @param val
 */
const handleGroupIdsShow = (val) => {
  return (
    groupList.value.filter((item) => item.id == val)[0] &&
    groupList.value.filter((item) => item.id == val)[0].name
  );
};

getOrgSearchAg();
getGroupList();
getList();
</script>
<style scoped>
.el-form-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
:deep(.el-drawer__header) {
  border-bottom: 1px solid gainsboro;
  height: 60px;
  margin-bottom: -5px;
}
:deep(.el-dialog__header) {
  margin-top: -20px;
}
.xztj {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
  :deep(.el-radio-group) {
    display: flex !important;
    flex-direction: column;
    align-items: flex-start !important;
  }
}
.xx {
  position: relative;
  top: -80px;
}
</style>
